package com.summer.shopping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.shopping.domain.common.req.ReqHolder;
import com.summer.shopping.domain.table.*;
import com.summer.shopping.domain.table.dto.OrderCreateDTO;
import com.summer.shopping.domain.table.dto.PageDTO;
import com.summer.shopping.domain.table.vo.*;
import com.summer.shopping.mapper.*;
import com.summer.shopping.service.OrderService;
import com.summer.shopping.utils.PageResult;
import com.summer.shopping.utils.Result;
import com.summer.shopping.utils.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrderService {
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    AccountMapper accountMapper;
    @Autowired
    QuanMapper quanMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    BagMapper bagMapper;
    @Override
    public Result createOrder(OrderCreateDTO orderCreateDTO) {
        Orders orders = new Orders();
        orders.setAddressId(orderCreateDTO.getAddressId());
        Long userId = ReqHolder.getUserId();
        orders.setUserId(userId);
        //查看库存是否充裕

        //查出产品号
        List<Long> productIds = orderCreateDTO.getProductIds();
        List<Long> numbers1 = orderCreateDTO.getNumbers();
        List<Product> products = productMapper.selectBatchIds(productIds);
        //建立产品号和所要扣减的产品数目的映射关系
        HashMap<Long, Long> pdIdAndpdNum = new HashMap<>();
        for (int i = 0; i < productIds.size(); i++) {
            pdIdAndpdNum.put(productIds.get(i),numbers1.get(i));
        }
        //判断库存是否充足
        for(Product product:products){
            //订单里想要的
            Long orderNum = pdIdAndpdNum.get(product.getId());
            //库存
            Integer stockNum = product.getNumbers();
            if(orderNum>stockNum){
                return Result.error("库存不足");
            }
        }

        //处理商品id
        String s = integerList2string(orderCreateDTO.getProductIds());
        orders.setProductIds(s);
        //处理商品数目
        s = integerList2string(orderCreateDTO.getNumbers());
        orders.setNumbers(s);

        //创建订单号
        orders.setOrderNumber(String.valueOf(System.currentTimeMillis()));

        // 计算该订单需要多少钱
        double sum =0 ;
        List<Long> numbers = orderCreateDTO.getNumbers();
        for(int i =0;i<products.size();i++){
            Product product = products.get(i);
            sum = sum+product.getPrice()*numbers.get(i);
        }
        //自己选的用哪个券
        Long bagId = orderCreateDTO.getBagId();
        //使用优惠券
        if(bagId != null){
            // 先查bag表
            Bag bag = bagMapper.selectById(bagId);
            if(bag == null){
                return Result.error("用户优惠券不存在");
            }
            // 再查quan表
            Long quanId = bag.getGoodsId();
            Quan quan = quanMapper.selectById(quanId);
            if(quan != null){
                String[] minusAndCondition = quan.getWorth().split(":");
                if(quan.getLinkProdId()==0){
                    //总和大于满减才可以进行
                    if(sum>Integer.parseInt(minusAndCondition[1])){
                        sum=sum-Integer.parseInt(minusAndCondition[0]);
                    }
                }else{
                    //有的优惠券只能对部分商品使用，但一个商品可以买好多件
                    for(int i =0;i<products.size();i++)
                    {
                        Product product = products.get(i);
                        Long id = product.getId();
                        //针对于这一件商品且价格大于满减时
                        if(id.equals(quan.getLinkProdId())&&product.getPrice()*numbers.get(i)>Integer.parseInt(minusAndCondition[1])){
                            sum=sum-Integer.parseInt(minusAndCondition[0]);
                        }
                    }
                }
            } else {
                // 优惠券类型不存在
                return Result.error("优惠券类型不存在");
            }
        }

        orders.setAmount(sum);
        orders.setCreateTime(LocalDateTime.now());
        ordersMapper.insert(orders);

        //订单来自于购物车
        if(Boolean.TRUE.equals(orderCreateDTO.getIsShoppingCart())){
            //清空购物车中对应商品
            for (Long productId:productIds) {
                QueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new QueryWrapper<>();
                shoppingCartQueryWrapper.eq("user_id",userId);
                shoppingCartQueryWrapper.eq("product_id",productId);
                shoppingCartMapper.delete(shoppingCartQueryWrapper);
            }
        }
        HashMap<String, Long> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("orderId",orders.getId());
        return Result.ok(stringStringHashMap);
    }


    @Override
    public Result queryPay(Integer orderId) {
        Orders orders = ordersMapper.selectById(orderId);
        Long userId = ReqHolder.getUserId();
//        Long userId=1l;
        //返回订单号，当前余额
        OrderCreateVo orderCreateVo = new OrderCreateVo();
        orderCreateVo.setOrderTime(orders.getCreateTime());
        orderCreateVo.setOrderNumber(orders.getOrderNumber());
        //查余额
        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("user_id",userId);
        Account account = accountMapper.selectOne(accountQueryWrapper);
        orderCreateVo.setBalance(account.getBalance());
        orderCreateVo.setAmount(orders.getAmount());
        return Result.ok(orderCreateVo);
    }

    @Override
    public Result myOrder(PageDTO pageDTO) {
        //设定排序字段
        Page<Orders> ordersPage = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        OrderItem orderItem = new OrderItem().setAsc(false).setColumn("create_time");
        ordersPage.addOrder(orderItem);

        Long userId = ReqHolder.getUserId();
        //设置查询字段
        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        ordersQueryWrapper.eq("user_id",userId);
        //查询
        Page<Orders> ordersPage1 = ordersMapper.selectPage(ordersPage, ordersQueryWrapper);
        //封装VO
        List<Orders> records = ordersPage1.getRecords();
        long total = ordersPage1.getTotal();
        List<OrdersPageVo> productPageVos = new ArrayList<>();
        for(Orders orders:records){
            //设置部分参数
            OrdersPageVo ordersPageVo = new OrdersPageVo();
            ordersPageVo.setOrderId(orders.getId());
            ordersPageVo.setOrderNumber(orders.getOrderNumber());
            ordersPageVo.setCreateTime(orders.getCreateTime());
            ordersPageVo.setAmount(orders.getAmount());
            ordersPageVo.setOrderStatus(orders.getOrderStatus());
            //设置商城部分
            ArrayList<Long> numbers = string2IntegerList(orders.getNumbers());
            ArrayList<Long> productIds = string2IntegerList(orders.getProductIds());
            ArrayList<OrderProductItemVo> orders1 = new ArrayList<>();
            List<Product> products = productMapper.selectBatchIds(productIds);
            //建立产品号和所要扣减的产品数目的映射关系
            HashMap<Long, Long> pdIdAndpdNum = new HashMap<>();
            for (int i = 0; i < productIds.size(); i++) {
                pdIdAndpdNum.put(productIds.get(i),numbers.get(i));
            }

            for (Product product: products) {
                OrderProductItemVo orderProductItemVo = new OrderProductItemVo();
                orderProductItemVo.setImg(product.getImg());
                orderProductItemVo.setPrice(product.getPrice());
                orderProductItemVo.setNumber(pdIdAndpdNum.get(product.getId()));
                orderProductItemVo.setName(product.getName());
                orders1.add(orderProductItemVo);
            }
            ordersPageVo.setOrderProductItemVo(orders1);
            productPageVos.add(ordersPageVo);
        }

        OrdersPagePlusVo ordersPagePlusVo = new OrdersPagePlusVo();
        ordersPagePlusVo.setOrdersPageVo(productPageVos);
        ordersPagePlusVo.setTotal(total);

        return Result.ok(ordersPagePlusVo);
    }

    @Override
    @Transactional
    public Result pay(Integer id) {
        Long userId = ReqHolder.getUserId();
//        Long userId =1l;
        Orders orders = ordersMapper.selectById(id);

  //      if(orders.getUserId().equals(userId))return Result.error("只能对自己的订单进行支付");
        if(orders.getOrderStatus().equals(Constants.PAID))return Result.error("请勿重复支付");

        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("user_id",userId);
        Account account = accountMapper.selectOne(accountQueryWrapper);
        //查出产品号
        ArrayList<Long> pdIds = string2IntegerList(orders.getProductIds());
        ArrayList<Long> pdNums = string2IntegerList(orders.getNumbers());
        //查出来之后，产品号会乱
        List<Product> products = productMapper.selectBatchIds(pdIds);
        //建立产品号和所要扣减的产品数目的映射关系
        HashMap<Long, Long> pdIdAndpdNum = new HashMap<>();
        for (int i = 0; i < pdIds.size(); i++) {
            pdIdAndpdNum.put(pdIds.get(i),pdNums.get(i));
        }
        //判断库存是否充足
        for(Product product:products){
            //订单里想要的
            Long orderNum = pdIdAndpdNum.get(product.getId());
            //库存
            Integer stockNum = product.getNumbers();
            if(orderNum>stockNum){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error(product.getName()+"库存不足");
            }
        }
        //判断余额是否充足
        if(orders.getAmount()>account.getBalance()){
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("余额不足");
        }
        //批量扣减库存，需要手动开启mybatis-plus支持的批量扣减内存
        productMapper.batchReduceStock(pdIdAndpdNum);

        //扣减余额
        //增添消费额
        account.setBalance(account.getBalance()- orders.getAmount());
        account.setConsumption(account.getConsumption() + orders.getAmount());
        accountMapper.updateById(account);

        //改变订单状态
        ordersMapper.updateById(orders.setOrderStatus(Constants.PAID));

        return Result.ok("success!");
    }
    private  String integerList2string(List<Long> list) {
        StringBuilder sb = new StringBuilder();
        for (Long productid : list) {
            sb.append(productid.toString()+",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
    private  ArrayList<Long> string2IntegerList(String s) {
        String[] split = s.split(",");
        ArrayList<Long> integers = new ArrayList<>();
        for(String  str:split){
            integers.add(Long.parseLong(str));
        }
        return integers;
    }

}
